//
//  VideoDataViewController.m
//  NEWS_W_Y_S
//
//  Created by lanou3g on 15/10/14.
//  Copyright © 2015年 lanou3g.jake. All rights reserved.
//

#import "VideoDataViewController.h"

#import "VideoDataCell.h"
#import "VideoModel.h"
#import "VideoDataModel.h"
#import "MJRefresh.h"

#import "UrlConnection.h"
#import "AFNetworking.h"

#define VideoDataUrl @"http://c.3g.163.com/nc/video/detail/%@.html"
//VB51582R2
@interface VideoDataViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,retain)NSMutableArray *allEventsArray;

//@property(nonatomic,strong) AVPlayer *player;

//@property(nonatomic,strong) AVPlayerLayer *playerLayer;

@property(nonatomic,strong) MPMoviePlayerController *moviePlayer;

@property(nonatomic,copy)NSString *urlString;

@property(nonatomic,strong)UITableView *videoDataTableView;

@end

@implementation VideoDataViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];

    self.navigationItem.title = self.videoModel.title;
    self.videoDataTableView.separatorStyle = UITableViewCellAccessoryNone;
    self.urlString = self.videoModel.mp4_url;
    UIBarButtonItem *leftBarButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back"] style:UIBarButtonItemStylePlain target:self action:@selector(back:)];
    self.navigationItem.leftBarButtonItem = leftBarButton;

    [self loadData];
    
   [self layoutViews];

}

-(void)loadData{

    AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
    [securityPolicy setAllowInvalidCertificates:YES];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager setSecurityPolicy:securityPolicy];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
 
    NSString *str = [NSString stringWithFormat:VideoDataUrl,self.videoModel.vid] ;

    [manager GET:str parameters:nil success:^(AFHTTPRequestOperation * operation, id responseObject) {
        
        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
   
        NSArray *array = dict[@"recommend"];
        self.allEventsArray = [NSMutableArray array];
        for (NSDictionary *dic in array) {
        VideoDataModel *model = [[VideoDataModel alloc] init];
        [model setValuesForKeysWithDictionary:dic];
        [self.allEventsArray addObject:model];
        }
       NSLog(@"===%ld",self.allEventsArray.count);
        [self.videoDataTableView reloadData];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError * error) {
        NSLog(@"解析失败");
    }];
    
    [self loadViews];
    
}

-(void)layoutViews {
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, 230)];
    UILabel *headerNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 210, self.view.frame.size.width, 30)];
    headerNameLabel.backgroundColor = [UIColor whiteColor];
    headerNameLabel.text = @"推荐";
    headerNameLabel.textColor = [UIColor redColor];
    headerNameLabel.textAlignment = NSTextAlignmentCenter;
    headerNameLabel.font = [UIFont systemFontOfSize:25];
    [headerView addSubview:headerNameLabel];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(5, 239, self.view.frame.size.width - 10, 1)];
    label.backgroundColor = [UIColor colorWithWhite:0.814 alpha:1.000];
    [headerView addSubview:label];
    
    self.moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL URLWithString:self.urlString]];
    _moviePlayer.view.frame = CGRectMake(0, 0, self.view.frame.size.width, 200);
    _moviePlayer.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [headerView addSubview:self.moviePlayer.view];
    [self.moviePlayer play];
    
//    self.player = [[AVPlayer alloc] initWithURL:[NSURL URLWithString:self.urlString]];
//    AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
//        playerLayer.frame = CGRectMake(0, 0, self.view.frame.size.width, 200);
//    self.playerLayer = playerLayer;
//    [headerView.layer addSublayer:playerLayer];
//    [self.player play];
    
    [self.view addSubview:headerView];
    
    self.videoDataTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 304, self.view.frame.size.width, self.view.frame.size.height - 304)];
    self.videoDataTableView.dataSource = self;
    self.videoDataTableView.delegate = self;
    [self.view addSubview:self.videoDataTableView];
}

- (void)loadViews
{
    if (self.allEventsArray.count == 0) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.videoDataTableView.frame.size.width, self.videoDataTableView.frame.size.height)];
        view.backgroundColor = [UIColor whiteColor];
        view.alpha = 1.0;
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(130, 160, 120, 50)];
        label.numberOfLines = 0;
        label.textAlignment = NSTextAlignmentCenter;
        label.text = @"暂无推荐视频\n再去看看别的吧";
        [view addSubview:label];
        [self.videoDataTableView addSubview:view];
        
        UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"play"]];
        imageView.frame = CGRectMake(160, 100, 55, 55);
        imageView.alpha = 0.5;
        [view addSubview:imageView];
    }
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
   // NSLog(@"%ld",self.allEventsArray.count);
    return self.allEventsArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    static NSString *identifier = @"VideoDataCell";
    VideoDataCell *cell = (VideoDataCell *)[tableView cellForRowAtIndexPath:indexPath];
    if (cell == nil) {
        cell = [[VideoDataCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    VideoDataModel *videoDataModel = self.allEventsArray[indexPath.row];
    [cell videoData:videoDataModel];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    VideoDataCell *cell = (VideoDataCell*)[tableView cellForRowAtIndexPath:indexPath];
    cell.videoNameLabel.textColor = [UIColor redColor];
    
    [self.moviePlayer stop];
    self.urlString = ((VideoDataModel *)self.allEventsArray[indexPath.row]).mp4_url;
    [_moviePlayer setContentURL:[NSURL URLWithString:self.urlString]];
    [_moviePlayer play];
    
//    [self.player pause];
//    self.urlString = ((VideoModel *)self.allEventsArray[indexPath.row]).mp4_url;
//    [AVPlayer playerWithURL:[NSURL URLWithString:self.urlString]];
//    [self.player play];
    
    self.navigationItem.title = ((VideoDataModel *)self.allEventsArray[indexPath.row]).title;
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    VideoDataCell *cell = (VideoDataCell*)[tableView cellForRowAtIndexPath:indexPath];
    cell.videoNameLabel.textColor = [UIColor blackColor];
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 120;
}

- (void)back:(UIBarButtonItem *)leftBarButtonItem
{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)addNotification{
    NSNotificationCenter *nottificationCenter = [NSNotificationCenter defaultCenter];
    [nottificationCenter addObserver:self selector:@selector(mediaPlayerPlaybackStateChanger:) name:MPMoviePlayerPlaybackStateDidChangeNotification object:self.moviePlayer];
    [nottificationCenter addObserver:self selector:@selector(mediaPlayerPlaybackFinished:) name:MPMoviePlayerPlaybackDidFinishNotification object:self.moviePlayer];
}

// 播放状态改变 注意播放完成时的状态的暂停
-(void)mediaPlayerPlaybackStateChanger:(NSNotification *)notification{
    switch (self.moviePlayer.playbackState) {
        case MPMoviePlaybackStatePlaying:
            NSLog(@"正在播放");
            break;
        case MPMoviePlaybackStatePaused:
            NSLog(@"播放暂停");
            break;
        case MPMoviePlaybackStateStopped:
            NSLog(@"播放停止");
            break;
        default:
            NSLog(@"播放状态是%li",self.moviePlayer.playbackState);
            break;
    }
}


//播放完成

-(void)mediaPlayerPlaybackFinished:(NSNotification *)notification{
    
    MPMoviePlayerController *movie =[notification object];
    //销毁播放通知
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:movie];
    [movie.view removeFromSuperview];
    
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"supportedInterfaceOrientations" object:self userInfo:@{@"surport" : [NSNumber numberWithBool:NO]}];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"supportedInterfaceOrientations" object:self userInfo:@{@"surport" : [NSNumber numberWithBool:YES]}];
}


@end
